package service

import (
	"time"
	"yun_image/dao"
	"yun_image/entity"
	"yun_image/util"
)

// SaveImg UserImg是用户的图片信息，YunImg是聚合图床的图片信息，多个UserImg可以对应同一个YunImg
// 保存图片时，会生成一个UserImg并保存，如果url在yunImg数据库中不存在，则生成一个YunImg并保存
func SaveImg(img *entity.UserImg, token string, url string, yunId string, categoryId int) error {
	var yunImg entity.YunImg
	err := dao.GetYunImgById(&yunImg, yunId)
	if err != nil {
		return err
	}
	// 如果数据库中不存在该yunImg，也就是这个图片是第一次上传到聚合图床，那么在数据库中增加该记录
	if yunImg.Id == "" {
		yunImg.Id = yunId
		yunImg.Url = url
		yunImg.UploadTime = time.Now().UnixMilli()
		err = dao.CreateYunImg(&yunImg)
		if err != nil {
			return err
		}
	}
	img.Account = util.UserTokenUtil.GetAccount(token)
	img.Url = url
	img.YunId = yunId
	img.CategoryId = categoryId
	img.CreateTime = time.Now().UnixMilli()
	err = dao.CreateUserImg(img)
	if err != nil {
		return err
	}
	err = dao.AddImgNumber(util.UserTokenUtil.GetAccount(token), 1)
	return err
}

// GetImgsByToken 根据用户token获取UserImg
func GetImgsByToken(imgs *[]entity.UserImg, token string) error {
	account := util.UserTokenUtil.GetAccount(token)
	err := dao.GetUserImgsByAccount(imgs, account)
	return err
}

// GetImgsByCategoryId 根据分类获取UserImg
func GetImgsByCategoryId(imgs *[]entity.UserImg, categoryId int) error {
	err := dao.GetUserImgsByCategoryId(imgs, categoryId)
	return err
}

// RemoveImgs 删除UserImg，是标记删除不是物理删除
func RemoveImgs(ids []int, account string) error {

	err := dao.DeleteUserImgs(ids, account)
	if err != nil {
		return err
	}
	err = dao.AddImgNumber(account, -1*len(ids))
	return err
}

// UpdateImgCategoryId 修改UserImg的分类
func UpdateImgCategoryId(userImgId int, categoryId int, account string) error {
	err := dao.UpdateUserImgCategoryId(userImgId, categoryId, account)
	return err
}

// GetImgsByShareId 根据图片分析的id获取UserImg
func GetImgsByShareId(imgs *[]entity.UserImg, shareId string) error {
	var share entity.ImageShare
	err1 := dao.GetImageShareById(&share, shareId)
	if err1 != nil {
		return err1
	}
	if share.Id == "" { // 没有查到ImageShare结果
		return nil
	}
	err2 := GetImgsByCategoryId(imgs, share.CategoryId)
	return err2
}
